// /**
//  * Created by Administrator on 2019/10/25.
//  */
//
// const ObjectID = require('mongodb').ObjectID;
// const Busboy = require('busboy');
// const fs = require("fs");
// const path = require('path');
//
//
// module.exports = {
//     handler: (req, res, next) => {
//
//         const busboy = new Busboy({headers: req.headers});
//
//         let id = new ObjectID();
//         console.log("~~~~~~~~~~~~~~~~~",id);
//         //第三方中间件接收上传
//         req.pipe(busboy);
//         busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
//             let saveTo = path.join("./static/", '', id.toString()+".mp3");
//             console.log(saveTo);
//             file.pipe(fs.createWriteStream(saveTo));
//
//         }).on('error', function (err) {
//             console.log("busboy error:" + err);
//             res.reply({code:30001,message:err,data:null});
//         })
//         .on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
//
//         }).on('finish', function () {
//             res.reply({code:0,message:null,data:{path:"/static/"+id.toString()+".mp3"}});
//         });
//     }
// }


/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
//const GridStore = require('mongodb').GridStore;
const GridFSBucket = require('mongodb').GridFSBucket;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const crypto = require('crypto');
const qiniu = require('yi-qiniu');
const ffmpeg = require('yi-ffmpeg');

module.exports = {
    handler: (req, res, next)=>{
        req.context=req.context||{};
        const authInfo = req.context.authInfo||{};
        const fsHash = crypto.createHash('md5');
        let filesize = 0;
        let fileData = [];

        const busboy = new Busboy({headers: req.headers});
        req.pipe(busboy);
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            const id = new ObjectID();

            let saveTo = path.join('./static/', '', filename);
            if(req.query.bgm){
                file.pipe(fs.createWriteStream(saveTo));
            }
            file.on('end', function () {
                if(req.query.bgm){
                    // let bgm =  path.join('./static/', '', req.query.bgm);
                    let bgm = req.query.bgm.replace(req.config.sys.resHost,'.');
                    let desPath = path.join('./static/', '', id.toString()+'.mp3');

                    ffmpeg.merger(saveTo,bgm,desPath,(err)=>{
                        if(err){
                            return res.reply({code:21000,message:'声音合成失败',info:err});
                        }
                        qiniu.uploadfile(desPath,filename,(e,r)=>{
                            if(e)
                            {
                                return res.err.unknownError(e);
                            }
                            const fileObj = {
                                _id: id,
                                filename: filename,
                                content_type: mimetype,
                                filesize: filesize,
                                url: r.url,
                                createTime:new Date(),
                                userId:authInfo._id,
                                userName:authInfo.name,
                                static:2,
                                md5:  fsHash.digest('hex'),
                                hash: r.hash
                            };
                            // res.json(fileObj);
                            res.reply({code:0,message:'上传成功',data:fileObj});
                            //将资源记录用户表
                            req.mongo.collection("file").insertOne(fileObj,()=>{
                                fs.unlinkSync(saveTo);
                                fs.unlinkSync(desPath);
                            });
                        },id.toString(),'sl-record','http://slrec.huiwanvip.com/');
                    });
                }else{
                    fileData = Buffer.from(fileData);
                    qiniu.uploadBuffer(fileData,filename,(e,r)=>{
                        if(e)
                        {
                            return res.err.unknownError(e);
                        }
                        const fileObj = {
                            _id: id,
                            filename: filename,
                            content_type: mimetype,
                            filesize: filesize,
                            url: r.url,
                            createTime:new Date(),
                            userId:authInfo._id,
                            userName:authInfo.name,
                            static:2,
                            md5:  fsHash.digest('hex'),
                            hash: r.hash
                        };
                        // res.json(fileObj);
                        res.reply({code:0,message:'上传成功',data:fileObj});
                        //将资源记录用户表
                        let fn = function () {
                        };
                        req.mongo.collection("file").insertOne(fileObj,fn);
                    },id.toString(),'sl-record','http://slrec.huiwanvip.com/');
                }
            }).on('error', function (err) {
                console.log("err:" + err)
                res.reply({code:60001,message:'上传失败：'+err});
            }).on('data', function (data) {
                fileData.push.apply(fileData, data);
                filesize += data.length;
                fsHash.update(data);
            });

        })
    }
};

